package cn.itcast.web.controller.cargo;


import cn.itcast.domain.cargo.*;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.cargo.PackService;
import cn.itcast.service.cargo.ShippingService;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.BeanMapUtils;
import cn.itcast.web.utils.DownloadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/shipping")
public class ShippingController extends BaseController {

    @Reference
    private ShippingService shippingService;

    @Reference
    private PackService packService;

    @Reference
    private ExportService exportService;

    /*
    url：/cargo/shipping/list.do
    作用：查询委托单列表
    参数： 无
    返回值： 委托单列表页面(cargo/shipping/shipping-list.jsp)
  */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "5") Integer pageSize){
        //1. 查询委托单列表
        //创建委托单的条件
        ShippingExample shippingExample = new ShippingExample();
        //创建时间排序
        shippingExample.setOrderByClause("create_time desc");
        PageInfo<Shipping> pageInfo = shippingService.findByPage(shippingExample,pageNum,pageSize);

        //2. 存储request域中
        request.setAttribute("pageInfo",pageInfo);
        //3. 回到页面
        return "cargo/shipping/shipping-list";

    }


    /*
      url：/cargo/shipping/toShipping.do
      作用：进入委托单添加页面
      参数：id 装箱单的id
      返回值： cargo/shipping/shipping-toShipping.jsp
   */
    @RequestMapping("/toShipping")
    public String toShipping(String id){
        Shipping shipping = new Shipping();
        request.setAttribute("id",id);
        //得到装箱单
        Pack pack = packService.findById(id);
        String exportIds = pack.getExportIds();
        //得到报运合同
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(Arrays.asList(exportIds));
        List<Export> exportList = exportService.findAll(exportExample);
        //定义一个变量信用证号
        String lcno = "";
        //定义一个变量 搬运单的总唛头
        String totalMarks = "";
        //定义一个变量装箱港
        String portOfLoading="";
        //定义一个卸货港
        String portOfDischar="";
        for (Export export : exportList) {
            lcno += export.getLcno();
            portOfLoading+=export.getShipmentPort();
            portOfDischar+=export.getDestinationPort();
            totalMarks += export.getMarks();
            export.setMarks(totalMarks);
            request.setAttribute("export",export);
        }
        shipping.setPortOfLoading(portOfLoading);
        shipping.setPortOfDischar(portOfDischar);
        shipping.setLcno(lcno);
        request.setAttribute("shipping",shipping);

        //返回到添加委托单的页面
        return "cargo/shipping/shipping-toShipping";
    }


    /*
     url：/cargo/shipping/edit.do
     作用：保存添加与保存修改
     参数：委托单对象
     返回值： 委托单列表
  */
    @RequestMapping("/edit")
    public String edit(Shipping shipping){
        //补充数据，因为这些数据是来自于登陆者
        //委托单的创建人
        shipping.setCreateBy(getLoginUserCompanyName());
        //委托单创建人所属的部门
        shipping.setCreateDept(getLoginUser().getDeptName());

        shippingService.save(shipping);
        return "redirect:/cargo/packing/list.do";
    }


    /*
     url：cargo/shipping/delete.do
     作用：删除委托单
     参数：委托单id
     返回值：购销列表
  */
    @RequestMapping("/delete")
    public String delete(String id){
        Shipping shipping = shippingService.findById(id);
        if (shipping.getState()==0){
            shippingService.delete(id);
        }
        return "redirect:/cargo/shipping/list.do";
    }

    /*
           url：/cargo/shipping/toView.do?id=31df2a93-10ae-404e-a83f-4225119d8600
           作用：查看委托单
           参数：id 委托单的id
           返回值：cargo/shipping/shipping-view
        */
    @RequestMapping("/toView")
    public String toView(String id){
        Shipping shipping = shippingService.findById(id);
        //存储到请求域中
        request.setAttribute("shipping",shipping);
        return "cargo/shipping/shipping-view";
    }


    /*
      url：/cargo/shipping/printExcel.do?id=31df2a93-10ae-404e-a83f-4225119d8600
      作用：下载电子报运Excel模式
      参数：id 报运单的id
      返回值：没有返回值，下载
   */
    @RequestMapping("/printExcel")
    @ResponseBody
    public void printExcel(String id) throws Exception {
        //1. 读取模板的输入流,读取resources目录下的资源使用类路径去读取， 如果读取的webapps目录下的内容使用servletContext
        ServletContext servletContext = session.getServletContext();
        InputStream inputStream = servletContext.getResourceAsStream("/make/xlsprint/tSHIPPINGORDER.xls");

        //2. 使用模板去创建一个工作薄
        Workbook workbook = new HSSFWorkbook(inputStream);
        //3. 得到工作单
        Sheet sheet = workbook.getSheetAt(0);
        Shipping shipping = shippingService.findById(id);
        //4. 得到第3行，设置第3行内容
        String shipper = shipping.getShipper();
        Row row = sheet.getRow(3);
        //得到第0个单元格
        Cell cell = row.getCell(0);
        cell.setCellValue(shipper);
        //得到第5个单元格
        String companyName = shipping.getCompanyName();
        Cell cell1 = row.getCell(5);
        cell1.setCellValue(companyName);

        //得到第8行。设置第8行的内容
        Row row1 = sheet.getRow(8);
        //得到第0个单元格
        Cell cell2 = row1.getCell(0);
        String consignee = shipping.getConsignee();
        cell2.setCellValue(consignee);

        //得到第15行
        Row row2 = sheet.getRow(15);
        //得到第0个单元格
        String notifyParty = shipping.getNotifyParty();
        Cell cell3 = row2.getCell(0);
        cell3.setCellValue(notifyParty);

        //得到第19行
        Row row3 = sheet.getRow(19);
        //得到第0个单元格
        Pack pack = packService.findById(id);
        String invoiceNo = pack.getInvoiceNo();
        Cell cell4 = row3.getCell(0);
        cell4.setCellValue(invoiceNo);
        //得到第3个单元格
        Date createTime = shipping.getCreateTime();
        Cell cell5 = row3.getCell(3);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(createTime);
        cell5.setCellValue(format);
        //得到第6个单元格
        String lcno = shipping.getLcno();
        Cell cell6 = row3.getCell(6);
        cell6.setCellValue(lcno);

        //得到第23行
        Row row4 = sheet.getRow(23);
        //得到第0个单元格
        String portOfLoading = shipping.getPortOfLoading();
        Cell cell7 = row4.getCell(0);
        cell7.setCellValue(portOfLoading);
        //得到第3个单元格
        String portOfTrans = shipping.getPortOfTrans();
        Cell cell8 = row4.getCell(3);
        cell8.setCellValue(portOfTrans);
        //得到第6个单元格
        String portOfDischar = shipping.getPortOfDischar();
        Cell cell9 = row4.getCell(6);
        cell9.setCellValue(portOfDischar);

        //得到第27行
        Row row5 = sheet.getRow(27);
        //得到第0个单元格
        Date loadingDate = shipping.getLoadingDate();
        String format1 = simpleDateFormat.format(loadingDate);
        Cell cell10 = row5.getCell(0);
        cell10.setCellValue(format1);
        //得到第2个单元格
        Date limtDate = shipping.getLimtDate();
        String format2 = simpleDateFormat.format(limtDate);
        Cell cell11 = row5.getCell(2);
        cell11.setCellValue(format2);
        //得到第3个单元格
        String isBatch = shipping.getIsBatch();
        Cell cell12 = row5.getCell(3);
        cell12.setCellValue(isBatch);
        //得到第5个单元格
        String isTrans = shipping.getIsTrans();
        Cell cell13 = row5.getCell(5);
        cell13.setCellValue(isTrans);
        //得到第7个单元格
        String copyNum = shipping.getCopyNum();
        Cell cell14 = row5.getCell(7);
        cell14.setCellValue(copyNum);

        //得到第31行
        Row row6 = sheet.getRow(31);
        //得到第0个单元格
        String marks = pack.getMarks();
        Cell cell15 = row6.getCell(0);
        cell15.setCellValue(marks);
        //得到第3个单元格
        Cell cell16 = row6.getCell(3);
        String descriptions = pack.getDescriptions();
        cell16.setCellValue(descriptions);
        //得到第6个单元格
        BigDecimal groosWeights = pack.getGroosWeights();
        Cell cell17 = row6.getCell(6);
        cell17.setCellValue(groosWeights+"KGS");
        //得到第8个单元格
        BigDecimal measurement = pack.getTotalVolume();
        Cell cell18 = row6.getCell(8);
        cell18.setCellValue(measurement+"M3");

        //得到37行
        Row row7 = sheet.getRow(37);
        Cell cell19 = row7.getCell(1);
        String specialConditio = shipping.getSpecialConditio();
        cell19.setCellValue(specialConditio);

        //9. 设置响应头，通知浏览器是下载
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  //这个类的本质就是一个数组
        //把工作薄的内容写到数组中
        workbook.write(byteArrayOutputStream);
        new DownloadUtil().download(byteArrayOutputStream,response,"委托单.xls");

    }
}
